package com.linsy.product.redis.mq.config;

import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import com.linsy.product.redis.mq.service.ConsumersMsgDecorator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 把mq任务注册到定时任务
 */
@Slf4j
public class RegisterCron implements ApplicationRunner {

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) {
        Set<Class<?>> set = KernelMqDataConfig.classSet;
        for (Class<?> c : set) {
            CronUtil.schedule(KernelMqDataConfig.cron, (Task) () -> {
                ConsumersMsgDecorator bean = (ConsumersMsgDecorator)applicationContext.getBean(c);
                if (bean != null) {
                    try {
                        bean.initConsumers();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }

        CronUtil.setMatchSecond(true);
        CronUtil.start();
    }
}
